<template>
  <div class="container">
    <!-- 卡片区域 -->
    <el-card>
      <!-- 新增试题按钮 -->
      <el-row type="flex" justify="end">
        <el-button
          type="success"
          size="small"
          icon="el-icon-edit"
          class="addQuestions"
          @click="$router.push('/questions/new')"
          >新增试题</el-button
        ></el-row
      >
      <!-- 搜索表单 -->
      <el-form ref="form" label-width="80px" :model="searchForm">
        <!-- 第一行表单 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="学科">
              <el-select v-model="searchForm.subjectID" placeholder="请选择">
                <el-option
                  v-for="item in subjectList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="二级目录">
              <el-select v-model="searchForm.catalogID" placeholder="请选择">
                <el-option
                  v-for="item in directoryList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="标签">
              <el-select v-model="searchForm.tags" placeholder="请选择">
                <el-option
                  v-for="item in tagList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="关键字">
              <el-input
                class="inline-input"
                v-model="searchForm.keyword"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第二行表单 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="试题类型">
              <el-select v-model="searchForm.questionType" placeholder="请选择">
                <el-option
                  v-for="item in questionTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="难度">
              <el-select v-model="searchForm.difficulty" placeholder="请选择">
                <el-option
                  v-for="item in difficultyList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="方向">
              <el-select v-model="searchForm.direction" placeholder="请选择">
                <el-option
                  v-for="item in directionList"
                  :key="item"
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="录入人">
              <el-select v-model="searchForm.creatorID" placeholder="请选择">
                <el-option
                  v-for="item in creatorList"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 第三行表单 -->
        <el-row>
          <el-col :span="6">
            <el-form-item label="题目备注">
              <el-input v-model="searchForm.remarks"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="企业简称">
              <el-input v-model="searchForm.shortName"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="城市">
              <el-row>
                <el-col :span="12">
                  <el-select v-model="searchForm.province" placeholder="请选择">
                    <el-option
                      v-for="item in provinceList"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-col>
                <el-col :span="12">
                  <el-select v-model="searchForm.city" placeholder="请选择">
                    <el-option
                      v-for="item in cityList"
                      :key="item"
                      :label="item"
                      :value="item"
                    >
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-row type="flex" justify="end">
              <el-button @click="clearSearchFrom">清除</el-button>
              <el-button type="primary" @click="onSearch">搜索</el-button>
            </el-row>
          </el-col>
        </el-row>
      </el-form>
      <!-- 搜索表单结束 -->

      <!-- 数据条数统计 -->
      <el-alert
        :title="`数据一共${questionCount}条`"
        type="info"
        show-icon
        :closable="false"
      >
      </el-alert>

      <!-- 基础面试题展示表格 -->
      <el-table :data="questionsList">
        <el-table-column prop="number" label="试题编号" min-width="120">
        </el-table-column>
        <el-table-column prop="subject" label="学科" min-width="70">
        </el-table-column>
        <el-table-column prop="catalog" label="目录"> </el-table-column>

        <el-table-column prop="questionType" label="题型" min-width="50">
          <template v-slot="{ row }">
            {{ farmatQuestionType(row.questionType) }}
          </template>
        </el-table-column>
        <el-table-column prop="question" label="题干" min-width="230">
          <template v-slot="{ row }">
            <span v-html="row.question"></span>
          </template>
        </el-table-column>
        <el-table-column label="录入时间" min-width="160">
          <template v-slot="{ row }">
            {{ row.addDate | parseTimeByString("{y}-{m}-{d} {h}:{i}:{s}") }}
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" min-width="60">
          <template v-slot="{ row }">
            {{ farmatDifficulty(row.difficulty) }}
          </template>
        </el-table-column>
        <el-table-column prop="creator" label="录入人" min-width="100">
        </el-table-column>
        <el-table-column label="操作" min-width="175">
          <template v-slot="{ row }">
            <!-- 预览按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="预览"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="primary"
                icon="el-icon-view"
                size="mini"
                plain
                circle
                @click="previewQuestionItem(row)"
              ></el-button>
            </el-tooltip>

            <!-- 编辑按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="编辑"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="success"
                icon="el-icon-edit"
                size="mini"
                plain
                circle
                @click="$router.push(`/questions/new?id=${row.id}`)"
              ></el-button>
            </el-tooltip>

            <!-- 删除按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="删除"
              placement="top"
              :enterable="false"
              :hide-after="2000"
            >
              <el-button
                type="danger"
                icon="el-icon-delete"
                circle
                size="mini"
                plain
                @click="deleteQuestion(row.id)"
              ></el-button>
            </el-tooltip>

            <!-- 加入精选题库按钮 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="加入精选题库"
              placement="top"
              :enterable="false"
              :hide-after="2000"
            >
              <el-button
                type="warning"
                icon="el-icon-check"
                size="mini"
                plain
                circle
                @click="addChoiceness(row.id)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-row type="flex" justify="end">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="this.searchForm.page"
          :page-sizes="[2, 5, 7, 10]"
          :page-size="this.searchForm.pagesize"
          layout=" prev, pager, next,sizes, jumper"
          :total="this.total"
        >
        </el-pagination>
      </el-row>
    </el-card>
    <jc-questions-preview
      ref="questionInfo"
      :preview-dialog.sync="previewDialog"
      :question="currentQuestion"
    ></jc-questions-preview>
  </div>
</template>

<script>
import { simple } from '@/api/hmmm/subjects.js'
import { simple as directorys } from '@/api/hmmm/directorys.js'
import { simple as tags } from '@/api/hmmm/tags.js'
import { questionType, difficulty, direction } from '@/api/hmmm/constants.js'
// 引入城市数据
import { provinces, citys } from '@/api/hmmm/citys.js'
import { simple as creator } from '@/api/base/users.js'
import {
  list as questionsLists,
  remove,
  choiceAdd
} from '@/api/hmmm/questions.js'
import JcQuestionsPreview from '@/module-hmmm/components/jc-questions-preview.vue'

export default {
  name: 'Questions',
  data () {
    return {
      subjectList: [], // 学科列表
      directoryList: [], // 目录列表
      tagList: [], // 标签列表
      questionTypeList: [], // 题型列表
      difficultyList: [], // 难度列表
      directionList: [], // 方向列表
      cityList: [], // 地区列表
      provinceList: [], // 城市列表
      creatorList: [], // 录入人列表

      searchForm: {
        // 表单数据
        page: 1, // 当前页数
        pagesize: 5, // 页尺寸
        subjectID: null, // 学科id
        difficulty: null, // 难度
        questionType: null, // 试题类型
        tags: null, // 标签名称
        province: null, // 企业所在地省份
        city: null, // 企业所在城市
        keyword: null, // 关键字
        remarks: null, // 题目备注
        shortName: null, // 企业简称
        direction: null, // 方向
        creatorID: null, // 录入人
        catalogID: null // 目录
      },

      questionsList: [], // 基础面试题列表
      total: 0, // 基础面试题总条数
      previewDialog: false, // 控制预览对话框的显示
      currentQuestion: {}
    }
  },
  components: {
    JcQuestionsPreview
  },
  async created () {
    // 获取简单学科列表
    const list = await simple()
    this.subjectList = list.data
    // 获取试题难度列表
    this.questionTypeList = questionType
    // 获取难度列表
    this.difficultyList = difficulty
    // 获取方向列表
    this.directionList = direction
    // 获取城市列表
    this.provinceList = provinces()
    // 获取录入人列表
    const creatorList = await creator({ keyword: '' })
    this.creatorList = creatorList.data
    // 初始化表格
    this.getQuestionsList()
  },

  methods: {
    // 清空搜索表单
    clearSearchFrom () {
      this.searchForm = this.$options.data().searchForm
      this.getQuestionsList()
    },
    // 搜索基础面试题
    onSearch () {
      // 点击搜索时,默认查询第一页数据
      this.searchForm.page = 1
      this.getQuestionsList()
    },
    // 获取基础面试题列表
    async getQuestionsList () {
      const result = await questionsLists(this.searchForm)
      this.questionsList = result.data.items
      this.total = result.data.counts
    },
    // 数据条数的切换
    handleSizeChange (pagesize) {
      // 切换条数时,返回第一页
      this.searchForm.page = 1
      this.searchForm.pagesize = pagesize
      this.getQuestionsList()
    },
    // 当前页面的切换
    handleCurrentChange (page) {
      this.searchForm.page = page
      this.getQuestionsList()
    },
    // 格式化难度表格项
    farmatDifficulty (val) {
      // 服务器返回的是字符串数字???????????
      if (val) {
        return this.difficultyList.find((t) => t.value === Number(val)).label
      }
    },
    // 格式化题型表格项
    farmatQuestionType (val) {
      // 服务器返回的是字符串数字???????????
      if (val) {
        return this.questionTypeList.find((t) => t.value === Number(val)).label
      }
    },
    // 打开预览问题对话框
    async previewQuestionItem (row) {
      await this.$refs.questionInfo.getquestionInfo(row.id)
      this.currentQuestion = row
      this.previewDialog = true
    },
    // 删除基础题库项
    deleteQuestion (id) {
      this.$confirm('确认要删除吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async (action) => {
          try {
            await remove({ id: id })
            this.$message.success('删除成功')
            this.getQuestionsList()
          } catch (error) {
            console.error(error)
            this.$message.error('删除失败')
          }
        })
        .catch(() => {})
    },
    // 将基础题添加到精选题库
    addChoiceness (id) {
      this.$confirm('确认添加到精选题库吗', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async (action) => {
          try {
            await choiceAdd({ id: id, choiceState: 1 })
            this.$message.success('添加成功')
            this.$router.push('/questions/choice')
          } catch (error) {
            console.error(error)
            this.$message.error('添加失败')
          }
        })
        .catch(() => {})
    }
  },

  computed: {
    // 统计总条数
    questionCount () {
      return this.total
    }
  },
  watch: {
    // 监听学科数据变化，请求对应目录和标签列表
    async 'searchForm.subjectID' (val) {
      // 选择学科时，重置目录和标签
      this.searchForm.catalogID = null
      this.searchForm.tags = null
      this.directoryList = []
      this.tagList = []
      // 获取当前学科的目录和标签
      if (val) {
        // 清空操作时，阻止发送请求
        const directory = await directorys(val)
        this.directoryList = directory.data
        const results = await tags(val)
        this.tagList = results.data
      }
    },
    // 监听城市数据变化，获取对应的地区列表
    'searchForm.province' (val) {
      // 选择城市时,清空地区
      this.searchForm.city = null
      this.cityList = []
      // 获取当前城市的地区
      if (val) {
        // 清空操作，就不发送请求
        this.cityList = citys(val)
      }
    }
  }
}
</script>

<style scoped lang='less'>
.el-card {
  margin: 8px 12px 10px;
  padding: 26px;
}
/deep/ .el-card__body {
  padding: 0;
}
.addQuestions {
  margin-bottom: 17px;
}
.el-alert {
  margin-bottom: 17px;
}
.el-table {
  margin-bottom: 20px;
}
/deep/ .number {
  background: #f4f4f5;
  padding: 0;
  margin-right: 10px;
}
/deep/ .btn-next,
/deep/.btn-prev {
  background: #f4f4f5 !important;
  padding: 0;
  margin-right: 10px;
}
/deep/ .active.number {
  background: #409eff;
  color: #fff;
}
/deep/ .el-pagination__sizes .el-input__inner {
  width: 125px !important;
}
.el-select {
  width: 100% !important;
}
</style>
